package version1_3_1;

import java.io.*;
import java.nio.Buffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @program:IntelliJ IDEA
 * @Description:游戏的文件操作
 * @author:Mr.CheCheHuiBujianO
 * @data: 2022/7/13 11:55
 */
public class GameFileOperate1 {

    public void createFileBuffer(){
        String fileName = "GameResult.txt";
        File file = new File(fileName);
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     *@Description: 使用缓冲流进行数据的写入
     *@Param: [gameResult]
     *@return:void
     *@Author: Mr.Lin
     *@Date: 2022/7/13 12:39
     */
    public void FileBufferWriter(String gameResult)  {
        String fileName = "GameResult.txt";
        try {
        //  BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(fileName));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName,true)));
            if (gameResult != null){
                bufferedWriter.flush();//刷新缓冲流
                bufferedWriter.write(gameResult);
                bufferedWriter.newLine();

            }
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Map<Integer,String> FileBufferReader()  {
        String fileName = "GameResult.txt";
        Map<Integer,String> gameResultGroup = new HashMap<>();//游戏结果组合
        try {
            if (new File(fileName).exists()) {
                //如果文件存在就找到相对应的文档
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
                Integer gameTime = 0;
                String  gameResult = null;
                while((gameResult = bufferedReader.readLine()) != null){
                    gameTime++;
                    gameResultGroup.put(gameTime,gameResult);
                }
            }
            else{
                System.out.println("对不起，你貌似没进行过游戏");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return gameResultGroup;
}
}
